import Vue from 'vue'
import Router from 'vue-router'
import home from './home'
import profile from './profile'
import pay from './pay'
import store from '../store/store.js'
import $ from 'edom'

Vue.use(Router)

const router = new Router({
  routes: home.concat(profile, pay)
})

// 每个页面都强制验证是否授权登录
router.beforeEach((to, from, next) => {
  let share = $().getUrlOption('share')
  if (share && to.path.indexOf('detail') !== -1) {
    let bindseller = $().getUrlOption('id')
    // $().setCookies('detailId', bindseller, 5000)
    localStorage.setItem('detailId', bindseller)
    store.commit('bindseller', bindseller)
  }
  // 用户无论进入哪个页面，只要没有user_id记录，就进入启动页
  // alert(to.path)
  if (!store.state.user_id && to.path !== '/authorize') {
    $().setCookies('beforeLoginUrl', to.path, 5000)
    next('/authorize')
    return
  }
  // 如果用户后退进入启动页
  if (to.path === '/authorize' && store.state.user_id) {
    next('/index')
    return
  }
  // 如果用户绑定了商家，只让他看到这个商家
  if ((to.path === '/index' || to.path === '/service' || to.path === '/search') && store.state.bind_seller !== 0) {
    next('/detail/' + store.state.bind_seller)
    return
  }
  next()
})

export default router
